import express from 'express'
import { getResult, likeSql } from '../../../util/operateSql.js';
import { request } from 'http';
import fs, { createWriteStream } from 'fs'
import path from 'path'
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
var y = new Date().getFullYear()
var m = new Date().getMonth() + 1
var filepath = path.resolve(__dirname, '../../../' ,`uploads\/temp\/${y}-${m>9?m:'0'+m}\/`)
var router = express.Router();

const TABLE = 'resource.douyin'

const getList = async (req, res, next) => {
  const sql = likeSql(TABLE,req.query,'like')
  getResult(sql).then((result) => {
    req.datas = result
  }).catch(err => {
    res.json(req.app.locals.error(err))
  }).finally(() => {
    next()
  })
}

router.get('/list', getList, (req,res,next) => {
  const sql = likeSql(TABLE,req.query,'like')
  
  res.json(req.app.locals.success(req.datas))

})

router.get('/video',getList, (req,res,next) => {
  const video_url = req.datas[0].video_url

    
    // const buffer = Buffer.from(result)
    // 
    
    // fs.writeFileSync(`\/uploads\/temp\/${y}-${m>9?m:'0'+m}\/`,buffer)
    fs.mkdirSync(filepath,{recursive: true})
    const filepaths = filepath+'/temp.txt'

    // const steam = createWriteStream(filepaths)

    // steam.on('finish', () => {
    //   
    //   file.close();
    // }).on('error', (err)=>{
    //   
    //   fs.unlink(filepaths);
    // })

    request('http://139.198.117.15/file/2022-11/file_1669444898941.txt',(res) => {
      

      res.pipe(fs.createWriteStream(filepaths)).on('close',(err) => {
        console.log(
          "" +
            ` \x1B[32m同步完成,当前同步文件： ${path.basename(sync[item])}\x1B[0m   \x1B[33m path： ${base}/${path.basename(sync[item])}\x1B[0m      `
        );

        res.send(filepaths)
      })
    })
    // 
    


  
})

export default router